/*
 * forwardor.hpp
 *
 *  Created on: 2016年12月15日
 *      Author: work
 */

#ifndef APPS_FORWARD2_INC_FORWARDOR_HPP_
#define APPS_FORWARD2_INC_FORWARDOR_HPP_

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/smart_ptr/scoped_ptr.hpp>

class CForwardor{
public:
	typedef boost::shared_ptr<boost::asio::serial_port> serail_t;

public:
	void setA( serail_t& serial ){
		m_a = serial;
		setUpAReceived();
	}

	void setB( serail_t& serial ){
		m_b = serial;
		setUpBReceived();
	}

	void on_readA(const boost::system::error_code& error,size_t bytes_transferred ){
		if( !error ){
			setUpASend( m_bBuf,bytes_transferred );
		}else{
			delete this;
		}
	}

	void on_readB( const boost::system::error_code& error,size_t bytes_transferred ){
		if( !error ){
			setUpASend( m_bBuf,bytes_transferred );
		}else{
			delete this;
		}
	}

	void on_writeA( const boost::system::error_code& error ){
		if( !error ){
			setUpBReceived();
		}else
			delete this;
	}

	void on_writeB( const boost::system::error_code& error ){
		if( !error ){
			setUpAReceived();
		}else
			delete this;
	}

protected:
	inline void setUpAReceived(){
		m_a->async_read_some( boost::asio::buffer(m_aBuf,128),boost::bind(&CForwardor::on_readA,this,boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred));
	}

	inline void setUpBReceived(){
		m_b->async_read_some( boost::asio::buffer(m_bBuf,128),boost::bind(&CForwardor::on_readB,this,boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred));
	}

	inline void setUpASend( const unsigned char* buf,size_t& bytes_transfer ){
		m_a->async_write_some( boost::asio::buffer(buf,bytes_transfer),boost::bind(&CForwardor::on_writeA,this,boost::asio::placeholders::error));
	}

	inline void setUpBSend( const unsigned char* buf,size_t& bytes_transfer ){
		m_b->async_write_some( boost::asio::buffer(buf,bytes_transfer),boost::bind(&CForwardor::on_writeB,this,boost::asio::placeholders::error));
	}
private:
	serail_t m_a;
	serail_t m_b;

	unsigned char m_aBuf[128];
	unsigned char m_bBuf[128];
};


#endif /* APPS_FORWARD2_INC_FORWARDOR_HPP_ */
